<!-- src/views/device/trend/index.vue -->
<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      
      <el-form-item label="设备选择">
        <el-select 
          v-model="queryParams.deviceIds" 
          placeholder="请选择设备" 
          multiple 
          clearable 
          collapse-tags
          @change="handleDeviceChange"
          style="width: 300px;"
        >
          <el-option
            v-for="device in deviceList"
            :key="device.id"
            :label="device.deviceName"
            :value="device.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="测点选择">
        <el-select 
          v-model="queryParams.pointIds" 
          placeholder="请选择测点" 
          multiple 
          clearable 
          collapse-tags
          style="width: 300px;"
        >
          <el-option
            v-for="point in pointList"
            :key="point.id"
            :label="point.pointName"
            :value="point.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="数据类型">
        <el-select v-model="queryParams.dataType" placeholder="请选择数据类型" clearable>
          <el-option label="电阻" value="0"></el-option>
          <el-option label="电压" value="1"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 图表区域 -->
    <div class="chart-container">
      <div id="trendChart" style="width: 100%; height: 500px;"></div>
    </div>

    <!-- 数据表格 -->
 
  </div>
</template>

<script>
import { listDevice } from "@/api/device/device";
import { listPoint } from "@/api/device/point";
import { trendData } from "@/api/device/trend";
import * as echarts from 'echarts';

export default {
  name: "DeviceTrend",
  data() {
    return {
      // 查询参数
      queryParams: {
        deviceIds: [],
        pointIds: [],
        dataType: "0", // 默认显示电阻
        startTime: undefined,
        endTime: undefined
      },
      // 日期范围
      dateRange: [],
      // 设备列表
      deviceList: [],
      // 测点列表
      pointList: [],
      // 图表实例
      chart: null,
      // 表格数据
      tableData: [],
      // 选中的设备信息
      selectedDevices: []
    };
  },
  created() {
    // 初始化数据
    this.getDeviceList();
    // 默认查询最近7天的数据
    this.setDefaultDateRange();
  },
  mounted() {
    // 初始化图表
    this.initChart();
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    /** 设置默认日期范围（最近7天） */
    setDefaultDateRange() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      this.dateRange = [start, end];
    },
    
    /** 获取设备列表 */
    getDeviceList() {
      listDevice().then(response => {
        this.deviceList = response.rows || response.data;
      });
    },
    
    /** 设备选择变化事件 */
    handleDeviceChange(deviceIds) {
      this.queryParams.pointIds = [];
      if (deviceIds && deviceIds.length > 0) {
        this.getPointList(deviceIds.join(','));
        // 更新选中的设备信息
        this.selectedDevices = deviceIds.map(id => {
          const device = this.deviceList.find(d => d.id === id);
          return {
            id: id,
            name: device ? device.deviceName : `设备${id}`
          };
        });
      } else {
        this.pointList = [];
        this.selectedDevices = [];
      }
    },
    
    /** 获取测点列表 */
    getPointList(deviceIds) {
      listPoint({ deviceIds: deviceIds }).then(response => {
        this.pointList = response.rows || response.data;
      });
    },
    
    /** 初始化图表 */
    /** 初始化图表 */
initChart() {
  this.chart = echarts.init(document.getElementById('trendChart'));
  
  // 默认图表配置
  const option = {
    title: {
      text: '多设备数据趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross', // 十字准星指示器
        label: {
          backgroundColor: '#6a7985' // 坐标轴指示器文本标签背景色
        },
        lineStyle: {
          color: '#999', // 指示线颜色
          width: 1
        },
        crossStyle: {
          color: '#999'
        }
      },
      formatter: function(params) {
        let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
        params.forEach(param => {
          const value = param.value[1] !== null ? param.value[1] : '无数据';
          const unit = param.seriesName.includes('电阻') ? 'Ω' : 'V';
          result += `<div style="display: flex; align-items: center; margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: <strong>${value}${unit}</strong>
          </div>`;
        });
        return result;
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      padding: [8, 12],
      extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.15);'
    },
    legend: {
      type: 'scroll',
      top: 30,
      pageIconColor: '#2c3e50',
      pageTextStyle: {
        color: '#2c3e50'
      },
      data: []
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%', // 为dataZoom留出空间
      top: 80,
      containLabel: true
    },
    dataZoom: [
      {
        type: 'inside', // 内置型数据区域缩放
        xAxisIndex: [0], // 控制x轴
        start: 0, // 初始缩放范围开始百分比
        end: 100 // 初始缩放范围结束百分比
      },
      {
        type: 'slider', // 滑动条型数据区域缩放
        xAxisIndex: [0],
        bottom: '2%', // 放置在底部
        height: 20, // 滑动条高度
        borderColor: '#ddd',
        fillerColor: 'rgba(64, 158, 255, 0.2)', // 选中区域填充色
        backgroundColor: '#f5f5f5',
        handleStyle: {
          color: '#409EFF', // 手柄颜色
          borderColor: '#409EFF'
        },
        textStyle: {
          color: '#666'
        }
      }
    ],
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666',
        rotate: 45, // 标签旋转45度，避免重叠
        formatter: function(value) {
          // 简化时间显示，只显示时分秒
          if (value && typeof value === 'string') {
            const parts = value.split(' ');
            return parts.length > 1 ? parts[1].substring(0, 8) : value;
          }
          return value;
        }
      },
      axisTick: {
        alignWithLabel: true
      },
      data: []
    },
    yAxis: {
      type: 'value',
      name: '电阻值(Ω)',
      nameTextStyle: {
        color: '#666',
        padding: [0, 0, 0, 10]
      },
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666',
        formatter: function(value) {
          return value;
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    series: []
  };
  this.chart.setOption(option);
  
  // 添加图表事件监听
  this.chart.on('click', (params) => {
    console.log('图表点击事件:', params);
    if (params.componentType === 'series') {
      this.$message.info(`${params.seriesName} - 时间: ${params.name}, 数值: ${params.value[1]}`);
    }
  });
  
  // 添加全局点击事件，点击空白处可取消选中
  this.chart.getZr().on('click', (params) => {
    if (!params.target) {
      // 点击空白区域，可以执行一些操作，比如取消高亮
      this.chart.dispatchAction({
        type: 'downplay'
      });
    }
  });
  
  // 窗口大小改变时重绘图表
  window.addEventListener('resize', this.chart.resize);
},
    
    /** 搜索按钮操作 */
    handleQuery() {
      // if (this.queryParams.deviceIds.length === 0) {
      //   this.$message.warning('请至少选择一个设备');
      //   return;
      // }
      
      if(this.dateRange.length <= 0){
        this.$message.warning('请选择时间范围');
        return;
      }
      // 设置时间参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      
      // 调用API获取多设备数据
      trendData(this.queryParams).then(response => {
        const data = response.data;
        this.updateChart(data);
        // this.updateTable(data);
      });
    },
    
    /** 更新图表数据 */
    /** 更新图表数据 */
updateChart(data) {
  if (!data || !data.chartData) {
    this.$message.warning('暂无数据');
    return;
  }
  
  const chartData = data.chartData;
  const option = {
    xAxis: {
      data: chartData.times
    },
    legend: {
      data: chartData.legend.filter(name => name) // 过滤掉空值
    },
    series: chartData.series.map((series, index) => {
      // 为每个系列添加更丰富的交互样式
      return {
        ...series,
        emphasis: { // 高亮样式
          focus: 'series', // 高亮整个系列
          itemStyle: {
            borderWidth: 2,
            borderColor: '#fff',
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          lineStyle: {
            width: 3
          }
        },
        select: { // 选中样式
          itemStyle: {
            borderColor: '#000',
            borderWidth: 2
          }
        },
        markPoint: { // 标记点，显示最大值和最小值
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ],
          symbolSize: 60,
          label: {
            formatter: function(param) {
              return param.value !== null ? param.value.toFixed(2) : '无数据';
            }
          }
        },
        markLine: { // 标记线，显示平均值
          data: [
            { type: 'average', name: '平均值' }
          ],
          label: {
            formatter: function(param) {
              return param.value !== null ? `平均: ${param.value.toFixed(2)}` : '无数据';
            }
          }
        }
      };
    })
  };
  
  // 根据数据类型更新Y轴名称
  if (this.queryParams.dataType === '0') {
    option.yAxis = { 
      ...option.yAxis,
      name: '电阻值(Ω)',
      nameTextStyle: {
        color: '#666',
        padding: [0, 0, 0, 10]
      }
    };
  } else if (this.queryParams.dataType === '1') {
    option.yAxis = { 
      ...option.yAxis,
      name: '电压值(V)',
      nameTextStyle: {
        color: '#666',
        padding: [0, 0, 0, 10]
      }
    };
  }
  
  this.chart.setOption(option, true);
  
  // 添加一些交互提示
  if (chartData.series.length > 0) {
    this.$nextTick(() => {
      this.$message.success(`已加载 ${chartData.series.length} 个设备的数据趋势`);
    });
  }
},
    
    
    
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        deviceIds: [],
        pointIds: [],
        dataType: "0",
        startTime: undefined,
        endTime: undefined
      };
      this.pointList = [];
      this.tableData = [];
      this.selectedDevices = [];
      this.setDefaultDateRange();
      
      // 清空图表
      if (this.chart) {
        this.chart.clear();
      }
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 210px);
  margin-top: 20px;
}
</style>